<?php
namespace app\admin\controller;

use app\common\model\User as UserModel;
use app\common\controller\AdminBase;
use think\Config;
use think\Db;

/**
 * 用户管理
 * Class AdminUser
 * @package app\admin\controller
 */
class User extends AdminBase
{
    protected $user_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->user_model = new UserModel();
    }

    /**
     * 用户管理
     * @param string $keyword   关键字
     * @param int    $pid       推荐人id
     * @param int    $page
     * @return mixed
     */
    public function index($keyword = '',$pid = '', $page = 1)
    {
        $map = []; // 一张表查询
        $map_join = []; // 多表查询条件
        $parent_name = ''; // 推荐者
        if ($keyword) { // 关键字查询条件
            $map['user_name|mobile|email'] = ['like', "%{$keyword}%"];
            $map_join['u.user_name|u.mobile|u.email'] = ['like', "%{$keyword}%"];
        }
        if ($pid && isNum($pid)) {// 推荐关系查询
            // 查询推荐人信息
            $parent_name = $this->user_model->where('id',$pid)->value('user_name');
            if ($parent_name) {// 推荐人存在时进行查询
                $map['share_id'] = ['=' , $pid];
                $map_join['u.share_id'] = ['=' , $pid];
            }else{// 不存在
                $this->error('用户不存在!');
            }
        }
        $user_list  =   db('user')
                        ->where($map_join)
                        ->alias('u')
                        ->join('user_rank r','u.rank_id = r.id')
                        ->field('u.*,r.rank_name')
                        ->order('u.id DESC')->paginate(15, false, ['page' => $page]);
        $users['reg_integral']         = $this->user_model->where($map)->sum('reg_integral');          // 统计激活积分
        $users['re_reg_integral']      = $this->user_model->where($map)->sum('re_reg_integral');       // 统计释放激活积分
        $users['consume_integral']     = $this->user_model->where($map)->sum('consume_integral');      // 统计消费积分
        $users['re_consume_integral']  = $this->user_model->where($map)->sum('re_consume_integral');   // 统计释放消费积分
        $users['share_integral']       = $this->user_model->where($map)->sum('share_integral');        // 统计推荐积分
        $users['re_share_integral']    = $this->user_model->where($map)->sum('re_share_integral');     // 统计释放推荐积分
        $users['balance']  = $this->user_model->where($map)->sum('balance');                           // 统计余额宝
        $users['shop_money']  = $this->user_model->where($map)->sum('shop_money');                     // 统计商户余额
        $users['count']  = $this->user_model->where($map)->count('id');                                // 会员人数
        return $this->fetch('index', ['user_list' => $user_list, 'keyword' => $keyword, 'users' => $users , 'parent_name' => $parent_name]);
    }

    /**
     * 添加用户
     * @return mixed
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 保存用户
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'User');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $data['password'] = md5($data['password'] . Config::get('salt'));
                if ($this->user_model->allowField(true)->save($data)) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑用户
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $user = $this->user_model->find($id);

        return $this->fetch('edit', ['user' => $user]);
    }

    /**
     * 更新用户
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'User');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $user           = $this->user_model->find($id);
                if ($data['num']) {
                    if ($data['wallet_type']=='1') {
                        $type_name = 'reg_integral';;
                    }elseif ($data['wallet_type'] == '2') {
                        $type_name = 're_reg_integral';
                    }elseif ($data['wallet_type'] == '3') {
                        $type_name = 'consume_integral';
                    }elseif ($data['wallet_type'] == '4') {
                        $type_name = 're_consume_integral';
                    }elseif ($data['wallet_type'] == '5') {
                        $type_name = 'share_integral';
                    }elseif ($data['wallet_type'] == '6') {
                        $type_name = 're_share_integral';
                    }elseif ($data['wallet_type'] == '7') {
                        $type_name = 'balance';
                    }elseif($data['wallet_type'] == '8') {
                        $type_name = 'shop_money';
                    }
                    $up_user[$type_name] = $user[$type_name]+$data['num'];
                    // 插入变动记录
                    $log[] =  array(
                                'num'           => $data['num'],
                                'wallet_type'   => $data['wallet_type'],
                                'change_type'   => '16',
                                'time'          => time(),
                                'uid'           => $id,
                                'before_num'    => $user[$type_name],
                                'later_num'     => $up_user[$type_name],
                                'description'   => '管理员操作：'.$data['num'],
                            );
                    model('user')->allowField(true)->save($up_user,['id' => $id]);
                    model('fund_log')->saveAll($log);
                }
                
                $user->id       = $id;
                $user->user_name = $data['user_name'];
                $user->mobile   = $data['mobile'];
                $user->email    = $data['email'];
                $user->status   = $data['status'];
                if (!empty($data['password']) && !empty($data['confirm_password'])) {
                    $user->password = md5($data['password'] . Config::get('salt'));
                }
                if ($user->save() !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除用户
     * @param $id
     */
    public function delete($id)
    {
        if ($this->user_model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}